﻿using System.Collections.Generic;

namespace HaskellPlugin {
	/// <summary>
	/// Convert tokens to raw html text.
	/// </summary>
	class Formatter {
		static string SpanTag(string style, string body) {
			return "<span class = " + style + ">" 
						+ body + "</span>";
	  }
		
		static string ToHTMLTag(Token token) {
			switch (token.KindOfLexem) {
				case Token.Kind.ID:
					return SpanTag("Identifier", token.Lexem);

				case Token.Kind.StringConst:
					return SpanTag("StringConst", token.Lexem);

				case Token.Kind.Keyword:
					return SpanTag("Keyword", token.Lexem);

				case Token.Kind.TypeID:
					return SpanTag("TypeIdentifier", token.Lexem);

				case Token.Kind.Space:
					return "&nbsp;";
				
				case Token.Kind.Operator:
					return SpanTag("Operator", token.Lexem);
				
				case Token.Kind.NewLine:
					return "<br>";

				case Token.Kind.Undefined:
					return SpanTag("Undefined", token.Lexem);

				case Token.Kind.LineComment:
					return SpanTag("Comment", token.Lexem);
			}
			return "";
		}

		
		static string EscapeSymbols(string x) {
			var acc = "";
			foreach(var c in x) {
				if (c == '<')
					acc += @"&lt;";
				else if (c == '>')
					acc += @"&gt;";
				else if (c == '&')
					acc += @"&amp;";
				else acc += c;
			}
			return acc;
		}

		/// <summary>
		/// ToHTML is apply "token to tag" mapping for each token in the collection.
		/// </summary>
		/// <param name="tokens">Tokens will be mapped.</param>
		/// <returns>Raw HTML source text.</returns>
		public static string ToHTML(IEnumerable<Token> tokens) {
			var acc = "";
			foreach (var token in tokens)
				acc += ToHTMLTag(new Token(EscapeSymbols(token.Lexem), token.KindOfLexem));
			return acc;
		}
	}
}
